package com.apes.fa.model;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.DutyCenter;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = FaAssetInvest.CONST_TABLE_NAME)
public class FaAssetInvest extends Model {

    public static final String CONST_TABLE_NAME = "fa_asset_invest";

    @Id
    @Column(name = "id", nullable = false, length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "资产投资转出/售卖", prefix = "TZ%(company)", padding = 5)
    @Comment("单号")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("部门")
    private Dept dept;

    @Column(name = "asset_whereabouts")
    @Comment("资产去向")
    private String assetWhereabouts;

    @Column(name = "asset_out_type")
    @Comment("资产转出类型")
    private String assetOutType;

    @Column(name = "state")
    @Comment("状态")
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_uid", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveUid;

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate;

    @OneToMany(mappedBy = "faAssetInvest", cascade =  CascadeType.ALL, orphanRemoval = true)
    private List<FaAssetInvestItem> faAssetInvestItems = new ArrayList<>();

    public List<FaAssetInvestItem> getFaAssetInvestItems() {
        for (FaAssetInvestItem faAssetInvestItem : faAssetInvestItems) {
            faAssetInvestItem.setFaAssetInvest(this);
        }
        return faAssetInvestItems;
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

}
